package com.moyun.finance.service;

import com.moyun.finance.entity.*;
import com.moyun.finance.repository.OrgDeptRepository;
import com.moyun.finance.repository.OrgDeptUserMidRepository;
import com.moyun.finance.repository.OrgUserRepository;
import com.moyun.finance.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrgDeptUserMidService {
    @Autowired
    OrgDeptUserMidRepository odumr;
    @Autowired
    OrgDeptRepository odr;
    @Autowired
    OrgUserRepository our;

    public Response save(List<OrgDeptUserMid> odums){
        for(OrgDeptUserMid odum : odums){
            odum.setId(BaseUtil.uuid());
            odumr.save(odum);
        }
        return new Response("用户部门信息添加成功!",true);
    }

//    public Response update(List<OrgDeptUserMid> odums){
//        for(OrgDeptUserMid odum : odums){
//            odumr.save(odum);
//        }
//        return new Response("用户部门信息修改成功!",true);
//    }

    public Response delete(OrgDeptUserMid odum){
        odumr.delete(odum);
        return new Response("用户部门信息删除成功!",true);
    }

    //本部门下所有人
    public List<OrgUser> findAllUserByDept(String deptId){
        List<OrgUser> users =  new ArrayList<>();
        List<OrgDeptUserMid> odums = odumr.findByDeptId(deptId);
        for(OrgDeptUserMid odum : odums){
            String userId = odum.getUserId();
            OrgUser ou = our.findById(userId).orElse(null);
            users.add(ou);
        }
        return users;
    }

    //查询用户属于哪个部门
    public List<OrgDept> findUserDeptByUser(String userId){
        List<OrgDept> depts =  new ArrayList<>();
        List<OrgDeptUserMid> odums = odumr.findByUserId(userId);
        for(OrgDeptUserMid odum : odums){
            String deptId = odum.getDeptId();
            if(deptId != null){
                OrgDept od = odr.findById(deptId).orElse(null);
                depts.add(od);
            }
        }
        return depts;
    }

    //拼接角色名
    public String findUserDeptNameByUser(String userId){
        List<OrgDeptUserMid> odums = odumr.findByUserId(userId);
        String deptName = "";
        int index = 0;
        for(OrgDeptUserMid odum : odums){
            if(index > 0){
                deptName += ",";
            }
            String deptId = odum.getDeptId();
            OrgDept od = odr.findById(deptId).orElse(null);
            deptName += od.getDeptName();
        }
        return deptName;
    }

    public List<String> findUserDeptIdByUser(String userId){
        List<OrgDeptUserMid> odums = odumr.findByUserId(userId);
        List<String> deptIds = new ArrayList<>();
        for(OrgDeptUserMid odum : odums){
            deptIds.add(odum.getDeptId());
        }
        return deptIds;
    }
}
